var fs = require('fs');
var express = require('express');
var router = express.Router(); //创建一个路由容器router
var Students = require('./students');
const { log } = require('console');

//渲染首页
router.get('/students', function (req, res) {

    Students.find(function (err, students) {
        if (err) {
            return res.status(500).send('Server error');
        }
        res.render('index.html', {
            teachers: [
                { name: '李娜', taitle: '语文', photo: "/public/img/853d76292e6d49db8bb93fa7ed8eb3c1.png" },
                { name: '刘萍', taitle: '英语', photo: "/public/img/c32bf9a56561442d81d12c0929235de2.png" },
                { name: '陆野', taitle: '数学', photo: "/public/img/1613b7f353c640c78d07f9e8c7ec11f5.png" },
            ],
            students: students
        }
        );
    })
});
//渲染添加学生页面
router.get('/students/new', function (req, res) {
    res.render('newstudent.html')
    console.log('渲染成功')
});
//处理添加学生请求
router.post('/students/new', function (req, res) {
    //1.获取表单数据
    //2.处理
    // 将处理的数据存到json文件中以持久化
    // 3.发送响应
    //  把表单中的数据提取出来并转化成对象形式
    // 将添加的学生信息push 进去
    // 把对象转化成字符串
    // 把字符串写入文件
    var student = req.body;
    Students.save(student, function (err) {
        if (err) {
            return res.status(500).send('Server error');
        }
        res.redirect('/students');
    })
});
//渲染编辑页面
router.get('/students/edit', function (req, res) {
    Students.findbyid(req.query.id,function (err, student) {
        if (err) {
            return res.status(500).send('Server error');
        }
        res.render('edit.html', {
            thestudent: student
        })
    });


});
//处理编辑请求
router.post('/students/edit', function (req, res) {
    var thestudent = req.body;
    Students.update(thestudent,function (err) {        
        if (err) {
            return res.status(500).send('Server error');
        }
        res.redirect('/students');
    })
});

//处理删除请求
router.get('/students/delete', function (req, res) {
    console.log(req.query.id)    
    Students.delete(req.query.id,function(err){
        if(err){
            return res.status(500).send('Server error');
        }
        
        res.redirect('/students');        
    })
});

module.exports = router;
